package lc.com.lcpicturebackend.manager.app.chatmemory;

import lc.com.lcpicturebackend.exception.BusinessException;
import lc.com.lcpicturebackend.exception.ErrorCode;
import lc.com.lcpicturebackend.manager.app.MessageConverter;
import lc.com.lcpicturebackend.model.entity.ConversationMsg;
import lc.com.lcpicturebackend.service.ConversationMsgService;
import lc.com.lcpicturebackend.service.ConversationService;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Component
public class MysqlMemoryChatMemory implements ChatMemory {
    Map<String, List<Message>> conversationHistory = new ConcurrentHashMap();

    private final ConversationService conversationService;
    private final ConversationMsgService conversationMsgService;

    // 构造器注入
    public MysqlMemoryChatMemory(ConversationService conversationService,
                                 ConversationMsgService conversationMsgService) {
        this.conversationService = conversationService;
        this.conversationMsgService = conversationMsgService;
    }

    @Override
    public void add(String conversationId, List<Message> messages) {
        // this.conversationHistory.putIfAbsent(conversationId, new ArrayList());
        // ((List)this.conversationHistory.get(conversationId)).addAll(messages);
        List<ConversationMsg> collect = messages.stream()
                .map(msg -> MessageConverter.messageToObj(msg, conversationId))
                .collect(Collectors.toList());

        // 调用存储方法
        boolean save = conversationMsgService.saveBatch(collect, collect.size());
        if (!save) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "系统错误，请稍后重试！");
        }

        // this.conversationHistory.putIfAbsent(conversationId, new ArrayList());
        // ((List) this.conversationHistory.get(conversationId)).addAll(messages);
    }

    @Override
    public List<Message> get(String conversationId, int lastN) {

        List<ConversationMsg> all = conversationMsgService.lambdaQuery()
                .eq(ConversationMsg::getConversationId, conversationId)
                .orderByDesc(ConversationMsg::getCreateTime)
                .list();
        return all != null ? all.stream()
                .skip((long) Math.max(0, all.size() - lastN))
                .map(MessageConverter::objToMessage).
                collect(Collectors.toList()) : List.of();
    }

    @Override
    public void clear(String conversationId) {
        this.conversationHistory.remove(conversationId);
        conversationMsgService.lambdaUpdate().eq(ConversationMsg::getConversationId, conversationId).remove();
    }
}
